package com.mano.mall.gateway.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zj
 * @Description:
 * @Date: Created in 11:11 2020/9/23
 * @Modified By:
 */
@Component
@Primary
@Slf4j
public class SwaggerDocumentConfig implements SwaggerResourcesProvider {
    // 获取ApolloConfig 配置
    @ApolloConfig
    private Config config;

    private static final String APOLLO_SWAGGER_KEY="mano.swagger.document";

    private String swaggerDocuent;

    @Override
    public List<SwaggerResource> get() {
        // 开启监听，配置文件
        return resources();
    }

    /**
     * 从阿波罗服务器中获取resources
     *
     * @return
     */

    private List<SwaggerResource> resources() {
        List resources = new ArrayList<>();
        // 网关使用服务别名获取远程服务的SwaggerApi
        // 第二个参数是，如果获取不到，则设置为默认值
        String property = this.swaggerDocuent;
        if(StringUtils.isBlank(property)){
            property= config.getProperty(APOLLO_SWAGGER_KEY,"");
        }
        JSONArray jsonArray = JSONArray.parseArray(property);
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            String name = jsonObject.getString("name");
            String location = jsonObject.getString("location");
            String version = jsonObject.getString("version");
            resources.add(swaggerResource(name, location, version));
        }
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

    /**
     *  apollo 配置监听 默认是 监听 application
     * @param event
     */
    @ApolloConfigChangeListener
    private void swaggerChange(ConfigChangeEvent event){
        if(event.isChanged(APOLLO_SWAGGER_KEY)){
            String property = config.getProperty(APOLLO_SWAGGER_KEY, "");
            this.swaggerDocuent = property;
            log.warn("Apollo swagger key:"+APOLLO_SWAGGER_KEY+" new value:"+property);
        }
    }
}
